package com.winit.dataInit;

import com.winit.Application;
import com.winit.feature.model.Feature;
import com.winit.feature.repository.FeatureOperations;
import com.winit.feature.repository.FeatureRepository;
import com.winit.feature.service.IFeatureService;
import com.winit.indexing.model.Indexing;
import com.winit.indexing.model.IndexingId;
import com.winit.indexing.service.IIdexingService;
import com.winit.menu.service.IMenuService;
import com.winit.page.model.Page;
import com.winit.page.repository.PageRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class PagePrototypeInitializer {

    @Autowired
    private PageRepository pageRepository;
    @Autowired
    private IFeatureService featureService;
    @Autowired
    private IIdexingService indexingService;
    @Autowired
    private FeatureRepository featureRepository;
    @Autowired
    private FeatureOperations featureOperations;
    @Autowired
    private IMenuService menuService;

    @Test
    public void execute(){
        Iterable<Page> pages = pageRepository.findAll();
        Iterator<Page> pageIterator = pages.iterator();
        Page temp = null;
        while (pageIterator.hasNext()){
            temp = pageIterator.next();
            if (StringUtils.isEmpty(temp.getMenuId())){
                continue;
            }
            if (null == menuService.getMenuById(temp.getMenuId())){
                continue;
            }
            Indexing indexing = this.indexingService.getIndexing(new IndexingId("page_feature_indexing", temp.getId()));
            if (indexing == null){
                this.featureService.createPrototypeForPage(temp);
                continue;
            }
            if (!indexing.getIndexMap().keySet().contains("PROTOTYPE" + temp.getId())){
                this.featureService.createPrototypeForPage(temp);
            }
        }
        Iterable<Feature> features = featureRepository.findAll();
        Iterator<Feature> featureIterator = features.iterator();
        Feature tempFeature = null;
        while (featureIterator.hasNext()){
            tempFeature = featureIterator.next();
           if (StringUtils.isEmpty(tempFeature.getType())){
               Feature update = new Feature();
               update.setId(tempFeature.getId());
               update.setType("COMMON");
               featureOperations.updatePropertiesNotNullById(update);
           }
        }
    }

}
